/*
 * @Author: Zcl84765
 * @Date: 2020-04-09 18:12:36
 * @LastEditors: Zcl84765
 * @LastEditTime: 2023-01-28 16:33:54
 */
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/login.vue'
import Home from '@/views/Home.vue'
import Welcome from '@/views/Welcome.vue'
import Users from '@/views/user/Users.vue'
import Roles from '@/views/role/Roles.vue'
import GoodsCate from '@/views/goods/GoodsCate.vue'
import GoodsList from '@/views/goods/GoodsList.vue'
import demo1 from '@/views/demo/demo1/index.vue'
import demo2 from '@/views/demo/demo2/index.vue'

import NotFound from '@/views/NotFound.vue'
import store from './store'
Vue.use(Router)
const userRule = { path: '/users', component: Users }
const roleRule = { path: '/roles', component: Roles }
const goodsRule = { path: '/goods', component: GoodsList }
const categoriesRule = { path: '/categories', component: GoodsCate }
const demo1Rule = { path: '/demo1', component: demo1 }
const demo2Rule = { path: '/demo2', component: demo2 }

const mappingRule = {
  users: userRule,
  roles: roleRule,
  goods: goodsRule,
  categories: categoriesRule,
  demo1: demo1Rule,
  demo2: demo2Rule,
}

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/login',
      component: Login,
    },
    {
      path: '/home',
      component: Home,
      name: 'home',
      redirect: '/welcome',
      children: [{ path: '/welcome', component: Welcome }],
    },
    {
      path: '*',
      component: NotFound,
    },
  ],
})

// 路由导航守卫
router.beforeEach((to, from, next) => {
  // console.log(to, from)
  if (to.path == '/login') {
    next()
  } else {
    const token = store.state.token
    // console.log(token, 'lll')
    if (!token) {
      next('/login')
    } else {
      next()
    }
  }
  // next()
})

//  动态路由的添加
export function initMenu() {
  const rightList = store.state.rightList
  rightList.forEach((item) => {
    item.children.forEach((it) => {
      const temp = mappingRule[it.path]
      temp.meta = it.rights
      router.addRoute('home', temp)
    })
  })
}

export default router
